package com.ywu.third.exec.standard.exec.impl;

import com.ywu.boot.exception.YwuRuntimeException;
import com.ywu.common.gson.GsonUtils;
import com.ywu.file.sys.sdk.enter.YwuFileSysExec;
import com.ywu.third.exec.standard.entity.YwuThirdExecEntity;
import com.ywu.third.exec.standard.exec.YwuThirdExecEngine;
import com.ywu.third.exec.standard.exec.param.ParamParseCoreService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName YwuPython3ExecEngine
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/10/14 11:18
 * @Version 1.0
 **/
@Component
@Slf4j
public class YwuPython3ExecEngine implements YwuThirdExecEngine {

    @Autowired
    private YwuFileSysExec ywuFileSysExec;

    private static final String PYTHON_3_ENGINE_TYPE = "PYTHON3";

    @Autowired
    private ParamParseCoreService paramParseCoreService;

    /**
    * @Author GroundDemo
    * @Description 执行类型
    * @Date 9:03 2024/10/16
    * @Param []
    * @return java.lang.String
    **/
    @Override
    public String execType() {
        return PYTHON_3_ENGINE_TYPE;
    }

    /**
    * @Author GroundDemo
    * @Description 执行核心逻辑
    * @Date 9:03 2024/10/16
    * @Param [entity]
    * @return java.lang.Object
    **/
    @Override
    public Object exec(YwuThirdExecEntity entity) {
        // 解析参数
        Map<String, Object> paramMap = paramParseCoreService.parseThirdExecParam(entity);
        // 下载文件
        String filePath = downloadThirdFile(entity, ywuFileSysExec);
        // python执行的参数不需要参数名称，而且还是弱类型的数据，直接传入即可
        Collection<Object> params = paramMap.values();
        String[] args = new String[2 + params.size()];
        args[0] = "python3";
        args[1] = filePath;
        int index = 2;
        for (Object p : params) {
            if (p instanceof Map) {
                args[index] = GsonUtils.serialize(p);
            } else if (p instanceof List) {
                List temp = (List) p;
                if (temp.get(0) instanceof Map) {
                    args[index] = GsonUtils.serialize(p);
                } else {
                    args[index] = p.toString();
                }
            } else {
                args[index] = p.toString();
            }
            index++;
        }
        // 存储返回的结果
        StringBuilder resStr = new StringBuilder();
        log.debug("do python3 exec {}", Arrays.toString(args));
        try {
            Process process = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                resStr.append(line);
                resStr.append("\n");
            }
            in.close();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            log.error("python3 exec failed {}", e.getMessage());
            throw new YwuRuntimeException(e.getMessage());
        } finally {
            File file = new File(filePath);
            // 删除下载的文件
            file.delete();
        }
        if (StringUtils.isEmpty(resStr)) {
            return resStr;
        } else {
            String temp = resStr.substring(0, resStr.length() - 1);
            try {
                Object deserialize = GsonUtils.deserialize(temp, Object.class);
                return GsonUtils.serialize(deserialize);
            } catch (Exception e) {
                return temp;
            }
        }
    }
}
